var adminUserCtrl = myApp.controller('adminUserCtrl', ['$scope', '$rootScope', 'NgTableParams', function($scope, $rootScope, NgTableParams) {
	$rootScope.firstType = Tools.permissionList[5].permissionId;
	$rootScope.secondType = Tools.permissionList[5].sonPermission[1].permissionId;

	$scope.newUserItem = {};
	$scope.modUserItem = {};
	$scope.delUserItem = {};
	$scope.newPwd = "";
	$scope.sex = Tools.sex;
	// 分页
	$scope.pageList = [];
	$scope.curPage = 1;
	$scope.totalPage = 1;
	$scope.totalRow = 0;
	var PAGESIZE = 10;

	// 提示弹层
	$scope.msg = "";
	$scope.visible = false;

	$scope.range = function(n) {
		return new Array(n);
	};

    /**
     * 下拉列表获取全部角色
     * @return {[type]} [description]
     */
    $scope.getAllRoleList = function(cb) {
		var data = {};
		commonSrv.getAllRoleList(data, function(result) {
			if(typeof cb == 'function') {
				cb(result);
			}
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		}, function() {
			$scope.$apply();
		});
	};

	/**
	 * 获取用户信息列表
	 * @param  {[type]} curPage [当前页码]
	 * @return {[type]}         [description]
	 */
	$scope.getUserList = function(curPage) {
		// console.log("请求第"+curPage+"页");
		var data = {
			curPage: curPage,
			pageSize: PAGESIZE
		}
		commonSrv.getUserList(data, function(result) {
			var list = result.data;
			$scope.userList = new NgTableParams({count: PAGESIZE}, { counts: [],  dataset: list});
			
			// 获取分页信息
			var paginate = result.paginate;
			$scope.totalPage = paginate.totalPage;
			$scope.totalRow = paginate.totalRow;
			// 设置分页
			$scope.setPage(curPage);
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		}, function() {
			$scope.$apply();
		});
	};
	// 设置分页
	$scope.setPage = function(curPage) {
		var newPageList = [];
		if (curPage < 1 || curPage > $scope.totalPage) {
			alert("设置分页失败");
			return;
		}
		var SHOWSIZE = 5;
		// 总页数小于SHOWSIZE
		if($scope.totalPage <= SHOWSIZE) {
			for(var i=0; i<$scope.totalPage; i++) {
				newPageList.push(i+1);
			}
		// 总页数大于等于SHOWSIZE
		} else {
			if(curPage > 2) {
				// 最后5页
				if(($scope.totalPage - curPage) < 2) {
					for(var i = ($scope.totalPage - 5); i < $scope.totalPage; i++) {
						newPageList.push(i + 1);
					}
				} else {
					for (var i = (curPage - 3); i < ((curPage + 2) > $scope.totalPage ? $scope.totalPage : (curPage + 2)); i++) {
                        newPageList.push(i + 1);
                    }
				}
			} else {
				for(var i=0; i<SHOWSIZE; i++) {
					newPageList.push(i + 1);
				}
			}
		}
        $scope.pageList = newPageList;
        $scope.curPage = curPage;
	};
	//设置当前选中页样式
    $scope.isActivePage = function (page) {
        return $scope.curPage == page;
    };
    //上一页
    $scope.previous = function () {
        if($scope.curPage > 1) {
        	$scope.getUserList($scope.curPage - 1);
        }
    }
    //下一页
    $scope.next = function () {
        if($scope.curPage < $scope.totalPage) {
        	$scope.getUserList($scope.curPage + 1);
        }
    };

    // 新增
	/**
	 * 打开新增用户信息面板
	 * @return {[type]} [description]
	 */
	$scope.openAdd = function() {
		$scope.newUserItem = {
			name: '',
			userName: '',
			pwd: '',
			email: '',
			mobile: '',
			userroleIds: [],
			sex: {},
			warn: {
				name: '',
				userName: '',
				pwd: '',
				email: '',
				mobile: ''
			}
		};
		$("#addUserModel").modal({backdrop: 'static', keyboard: false, show: true});
	};
	/**
	 * 新增用户
	 * @param {[type]} item [description]
	 */
	$scope.addUser = function() {
		// 1.显示名
		$scope.watchName('new');
		// 2.登录名
		$scope.watchUserName('new');
		// 3.密码
		$scope.watchPwd('new');
		// 4.邮箱--可以为空
		$scope.watchEmail('new');
		// 5.手机号码--可以为空
		$scope.watchMobile('new');
		// 6.性别
		// 7.分配角色--可以为空
		var userroleIds = '';
		if(typeof $scope.newUserItem.userroleIds == 'object') {
			for(var i in $scope.newUserItem.userroleIds) {
				if(i != ($scope.newUserItem.userroleIds.length - 1) ) {
					userroleIds += $scope.newUserItem.userroleIds[i].userroleId+',';
				} else {
					userroleIds += $scope.newUserItem.userroleIds[i].userroleId;
				}
			}
		} else {
			userroleIds = '';
		}

		// 验证是否能提交
		if(!Tools.reg.isNull($scope.newUserItem.warn.name) || !Tools.reg.isNull($scope.newUserItem.warn.userName) || !Tools.reg.isNull($scope.newUserItem.warn.pwd) || !Tools.reg.isNull($scope.newUserItem.warn.email) || !Tools.reg.isNull($scope.newUserItem.warn.mobile) ) {
			alert("请修改表单");
			return;
		}

		// 性别
		var sex = 0;
		if($scope.newUserItem.sex == null) {
    		sex = 0;
    	} else if(!$scope.newUserItem.sex.id) {
    		sex = 0;
    	} else {
    		sex = $scope.newUserItem.sex.id;
    	}

		var data = {
			name: $scope.newUserItem.name,
			userName: $scope.newUserItem.userName,
			pwd: $scope.newUserItem.pwd,
			email: $scope.newUserItem.email || '',
			mobile: $scope.newUserItem.mobile,
			sex: sex,
			userroleIds: userroleIds
		};
		commonSrv.addUser(data, function(result) {
			if(result.status == 0) {
				$scope.msg = "新增成功";
				$scope.visible = true;						
				// $scope.getUserList($scope.curPage);
				$scope.getUserList(1);
				$("#addUserModel").modal('hide');
				$scope.newUserItem = {};
			}
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		}, function() {
			$scope.$apply();
		});
	};
	// 获取随机密码
	$scope.randomPassword = function(type) {
		if (type == 'new') {
			$scope.newUserItem.pwd = commonSrv.randomStr(false, 8);
		} else if (type == 'update') {
			$scope.newPwd = commonSrv.randomStr(false, 8);
		}
		$scope.watchPwd(type);
	};

	// 删除
	/**
	 * 打开删除用户信息面板
	 * @param  {[type]} item [description]
	 * @return {[type]}      [description]
	 */
	$scope.openDel = function(item) {
		$scope.delUserItem = item;
		$('#delUserModel').modal('show');
	};
	/**
	 * 删除用户
	 * @param  {[type]} item [description]
	 * @return {[type]}      [description]
	 */
	$scope.delUser = function(item) {
		var data = {
			userId: $scope.delUserItem.userId
		};
		commonSrv.delUser(data, function(result) {
			if(result.status == 0) {
				$scope.msg = "删除用户成功";
				$scope.visible = true;
				$("#delUserModel").modal('hide');
				$scope.delUserItem = {};
			}
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
			$("#delUserModel").modal('hide');
		}, function() {
			$scope.$apply();
		});
	};
	
	// 修改
	/**
	 * 打开修改用户信息面板
	 * @param  {[type]} item [description]
	 * @return {[type]}      [description]
	 */
	$scope.openEdit = function(item) {
		$scope.getUserById(item.userId, function(result) {
			$scope.modUserItem = result.data;
			// 登录名，去掉@xx后缀
			if($scope.modUserItem.userName && $scope.modUserItem.userName.indexOf("@") != -1) {
				var arr = $scope.modUserItem.userName.split("@");
				$scope.modUserItem.userName = arr[0];
			}
			if($scope.modUserItem.userroleIds == null || $scope.modUserItem.userroleIds == undefined) {
				$scope.modUserItem.userroleIds = [];
			} else {
				var temp = new Array();
				var array = $scope.modUserItem.userroleIds.split(",");
				// 分配角色
				for (var i in array) {
					for(var j in $scope.roleList) {
						if(array[i] == $scope.roleList[j].userroleId) {
							temp.push($scope.roleList[j]);
						}
					}
				}
				$scope.modUserItem.userroleIds = temp;
			}
			// 性别
			for (var i in $scope.sex) {
				if($scope.sex[i].id == $scope.modUserItem.sex) {
					 $scope.modUserItem.sex = $scope.sex[i];
				}
			}
			$scope.modUserItem.warn = {
				name : '',
				userName : '',
				email : '',
				mobile : ''
			};
			$("#editUserModel").modal({backdrop: 'static', keyboard: false, show: true});
		});
	}
	/**
	 * 修改用户信息
	 * @return {[type]}      [description]
	 */
	$scope.editUser = function() {
		// 1.显示名
		$scope.watchName('edit');
		// 2.登录名
		$scope.watchUserName('edit');
		// 3.邮箱--可以为空
		$scope.watchEmail('edit');
		// 4.手机号码--可以为空
		$scope.watchMobile('edit');
		// 5.性别

		// 6.分配角色
		var userroleIds = $scope.modUserItem.userroleIds;
		var userroleIdsStr = '';
		if(userroleIds == null || userroleIds == undefined) {
			userroleIdsStr = '';
		} else {
			for(var i in userroleIds) {
				if(i != userroleIds.length - 1) {
					userroleIdsStr += userroleIds[i].userroleId + ','
				} else {
					userroleIdsStr += userroleIds[i].userroleId;
				}
			}
		}

		// 验证是否通过
		if(!Tools.reg.isNull($scope.modUserItem.warn.name) || !Tools.reg.isNull($scope.modUserItem.warn.userName) || !Tools.reg.isNull($scope.modUserItem.warn.pwd) || !Tools.reg.isNull($scope.modUserItem.warn.email) || !Tools.reg.isNull($scope.modUserItem.warn.mobile) ) { 
			alert("请修改表单");
			return;
		}

		// 性别
		var sex = 0;
		if($scope.modUserItem.sex == null) {
    		sex = 0;
    	} else if(!$scope.modUserItem.sex.id) {
    		sex = 0;
    	} else {
    		sex = $scope.modUserItem.sex.id;
    	}

		var data = {
			email: $scope.modUserItem.email,
			mobile: $scope.modUserItem.mobile,
			name: $scope.modUserItem.name,
			sex: sex,
			userId: $scope.modUserItem.userId,
			userName: $scope.modUserItem.userName,
			userroleIds: userroleIdsStr
		};
		commonSrv.editUser(data, function(result) {
			if(result.status == 0) {
				$scope.msg = "修改成功";
				$scope.visible = true;
				$scope.getUserList($scope.curPage);
				$scope.modUserItem = {};
				$("#editUserModel").modal('hide');
			}
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		}, function() {
			$scope.$apply();
		});
	};

	// 重置密码
	/**
	 * 打开修改用户信息面板
	 * @param  {[type]} item [description]
	 * @return {[type]}      [description]
	 */
	$scope.openUpdatePwd = function(item) {
		$scope.modUserItem = angular.copy(item);
		$scope.newPwd = "";
		$scope.modUserItem.warn = {
			pwd: ""
		};
		$("#updatePwdModel").modal({backdrop: 'static', keyboard: false, show: true});
	};
	/**
	 * 修改用户信息
	 * @param  {[type]} item [description]
	 * @return {[type]}      [description]
	 */
	$scope.updatePwd = function(item) {
		// 重置密码
		$scope.watchPwd('edit');
		// 验证是否通过
		if(!Tools.reg.isNull($scope.modUserItem.warn.pwd)) {
			alert("请输入密码");
			return;
		}
		var data = {
			userId: $scope.modUserItem.userId,
			pwd: $scope.newPwd
		};
		commonSrv.updatePwd(data, function(result) {
			if(result.status == 0) {
				$scope.msg = "密码重置成功";
				$scope.visible = true;
				$scope.modUserItem = {};
				$scope.newPwd = "";
				$("#updatePwdModel").modal('hide');
			}
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		}, function() {
			$scope.$apply();
		});
	};

	/**
	 * 获取单个用户的信息
	 * @param  {[type]}   id [description]
	 * @param  {Function} cb [description]
	 * @return {[type]}      [description]
	 */
	$scope.getUserById = function(id, cb) {
		var data = {
			userId: id
		};
		commonSrv.getUserById(data, function(result) {
			if(result.status == 0) {
				cb(result);
			}
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		}, function() {
			$scope.$apply();
		});
	};

	// 验证
	// 1.用户名--2-16个字符(包含：中文、英文、数字)
	$scope.watchName = function (type) {
		var nullWarn = "显示名不能为空";
		var formatWarn = "请输入长度为2-16个字符(中文、英文、数字)";
		if(type == 'new') {
			if(Tools.reg.isNull($scope.newUserItem.name)) {
				$scope.newUserItem.warn.name = nullWarn;
			} else {
				if(!Tools.reg.name($scope.newUserItem.name)) {
					$scope.newUserItem.warn.name = formatWarn;
				} else {
					$scope.newUserItem.warn.name = "";
				}
			}
		} else if(type == 'edit') {
			if(Tools.reg.isNull($scope.modUserItem.name)) {
				$scope.modUserItem.warn.name = nullWarn;
			} else {
				if(!Tools.reg.name($scope.modUserItem.name)) {
					$scope.modUserItem.warn.name = formatWarn;
				} else {
					$scope.modUserItem.warn.name = "";
				}
			}
		}
	};
	// 2.登陆名--4-20个字符(英文、数字)
	$scope.watchUserName = function (type) {
		var nullWarn = "登陆名不能为空";
		var formatWarn = "请输入长度为4-20个字符(英文、数字)";
		if(type == 'new') {
			if(Tools.reg.isNull($scope.newUserItem.userName)) {
				$scope.newUserItem.warn.userName = nullWarn;
			} else {
				if(!Tools.reg.userName($scope.newUserItem.userName)) {
					$scope.newUserItem.warn.userName = formatWarn;
				} else {
					$scope.newUserItem.warn.userName = "";
				}
			}
		} else if(type == 'edit') {
			if(Tools.reg.isNull($scope.modUserItem.userName)) {
				$scope.modUserItem.warn.userName = nullWarn;
			} else {
				if(!Tools.reg.userName($scope.modUserItem.userName)) {
					$scope.modUserItem.warn.userName = formatWarn;
				} else {
					$scope.modUserItem.warn.userName = "";
				}
			}
		}
	};
	// 3.密码--6-20个字符(英文、数字)
	$scope.watchPwd = function (type) {
		var nullWarn = "密码不能为空";
		var formatWarn = "请输入长度为6-20个字符(英文、数字)";
		if(type == 'new') {
			if(Tools.reg.isNull($scope.newUserItem.pwd)) {
				$scope.newUserItem.warn.pwd = nullWarn;
			} else {
				if(!Tools.reg.pwd($scope.newUserItem.pwd)) {
					$scope.newUserItem.warn.pwd = formatWarn;
				} else {
					$scope.newUserItem.warn.pwd = "";
				}
			}
		} else if(type == 'edit') {
			if(Tools.reg.isNull($scope.newPwd)) {
				$scope.modUserItem.warn.pwd = nullWarn;
			} else {
				if(!Tools.reg.pwd($scope.newPwd)) {
					$scope.modUserItem.warn.pwd = formatWarn;
				} else {
					$scope.modUserItem.warn.pwd = "";
				}
			}
		}
	};
	// 4.email--正确email格式
	$scope.watchEmail = function (type) {
		var formatWarn = "请输入正确的邮箱格式";
		if(type == 'new') {
			if(!Tools.reg.isNull($scope.newUserItem.email) && !Tools.reg.email($scope.newUserItem.email)) {
				$scope.newUserItem.warn.email = formatWarn;
			} else {
				$scope.newUserItem.warn.email = "";
			}
		} else if(type == 'edit') {
			if(!Tools.reg.isNull($scope.modUserItem.email) && !Tools.reg.email($scope.modUserItem.email)) {
				$scope.modUserItem.warn.email = formatWarn;
			} else {
				$scope.modUserItem.warn.email = "";
			}
		}
	};
	// 4.email--正确email格式
	$scope.watchMobile = function (type) {
		var formatWarn = "请输入正确的手机号码";
		if(type == 'new') {
			if(!Tools.reg.isNull($scope.newUserItem.mobile) && !Tools.reg.mobile($scope.newUserItem.mobile)) {
				$scope.newUserItem.warn.mobile = formatWarn;
			} else {
				$scope.newUserItem.warn.mobile = "";
			}
		} else if(type == 'edit') {
			if(!Tools.reg.isNull($scope.modUserItem.mobile) && !Tools.reg.mobile($scope.modUserItem.mobile)) {
				$scope.modUserItem.warn.mobile = formatWarn;
			} else {
				$scope.modUserItem.warn.mobile = "";
			}
		}
	};
	// 初始化
	function init() {
		$scope.getUserList($scope.curPage);

		$scope.getAllRoleList(function(result) {
			$scope.roleList = result.data;
		});
		$(document).ready(function() {
			
		});
	}
	init();

}]);